﻿package net.wangit.view.unit.component;

import java.io.File;

import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.wangit.Path;
import net.wangit.context.ActionContext;
import net.wangit.context.LocalContext;
import net.wangit.framework.util.UnitDataUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBFactory;
import net.wangit.support.ReportWriter;
import net.wangit.util.Checker;
import net.wangit.util.ClassUtil;
import net.wangit.view.page.PageImpl;
import net.wangit.view.report.ReportSettings;
import net.wangit.view.unit.UnitComponent;
import net.wangit.view.unit.UnitWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class ReportUnitWriter implements UnitWriter {

	private static final Log log = LogFactory
			.getLog(net.wangit.view.unit.component.ReportUnitWriter.class);
	private static final int PDF_REPORT_EXPORTER = 1;

	public ReportUnitWriter() {
	}

	public void writePage(ActionContext ac, PageImpl page) throws Exception {
		ReportUnit ru = (ReportUnit) page.getUnit();
		String source = ru.getReportSource();
		File reportFile = new File((new StringBuilder(String.valueOf(Path
				.getRootPath()))).append("/").append(source).toString());
		JasperReport jasperReport = (JasperReport) JRLoader
				.loadObject(reportFile.getPath());
		ReportWriter writer;
		if (!Checker.isEmpty(ru.getReportWriter()))
			writer = (ReportWriter) ClassUtil.loadClass(ru.getReportWriter())
					.newInstance();
		else
			writer = new ReportWriter();
		ReportSettings settings = new ReportSettings();
		if (ReportUnitWriter.PDF_REPORT_EXPORTER == ru.getReportExporter())
			settings.setExporter(ReportSettings.PDF_REPORT_EXPORTER);
		else
			settings.setExporter(ReportSettings.HTML_REPORT_EXPORTER);
		DB db = DBFactory.getDB(ru.getDatasource());
		settings.setDB(db);
		settings.setSql(getSql(ac, ru, db));
		LocalContext lc = LocalContext.getLocalContext();
		writer.write(lc.getHttpServletRequest(), lc.getHttpServletResponse(),
				jasperReport, settings);
	}

	public String writeUnit(ActionContext ac, UnitComponent uc) {
		return "";
	}

	private String getSql(ActionContext ac, ReportUnit uc, DB db) {
		String dataExpression = uc.getDataExpression();
		if (Checker.isEmpty(dataExpression))
			return null;
		try {
			return UnitDataUtil.getSql(ac, uc, db);
		} catch (Exception e) {
			log.error("failed to get sql for report:", e);
			return null;
		}
	}

}
